/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.crypto

import java.io.FileInputStream
import java.security.KeyStore
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.TrustManagerFactory

class SslUtil {
    KeyStore keyStore;

    new(String keyStoreType) {
        keyStore = KeyStore.getInstance(keyStoreType === null ? "JKS" : keyStoreType);
    }

    def trustManageFactory() {
        var tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        return tmf;
    }

    def trustManageFactory(String sslKeyFilePath, String sslStorePwd) {
        try {
            keyStore.load(new FileInputStream(sslKeyFilePath), sslStorePwd.toCharArray());
            val tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            return tmf;
        } catch (Exception ex) {
            return null;
        }
    }

    def keyManageFactory(String sslKeyFilePath, String sslManagerPwd, String sslStorePwd) {
        try {
            keyStore.load(new FileInputStream(sslKeyFilePath), sslStorePwd.toCharArray());
            val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keyStore, sslManagerPwd.toCharArray());
            return kmf;
        } catch (Exception ex) {
            return null;
        }
    }
}
